package top.xiaoshuaila.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spi.service.contexts.SecurityContext;
import top.xiaoshuaila.config.security.JwtTokenUtil;
import top.xiaoshuaila.mapper.AdminRoleMapper;
import top.xiaoshuaila.mapper.RoleMapper;
import top.xiaoshuaila.pojo.*;
import top.xiaoshuaila.mapper.AdminMapper;
import top.xiaoshuaila.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.xiaoshuaila.util.AdminUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小帅啦
 * @since 2021-05-01
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;




    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if(captcha==null||!captcha.equalsIgnoreCase(code))
            return RespBean.error("验证码输入错误,请重新输");
        UserDetails userDetails =
                userDetailsService.loadUserByUsername(username);
        if(null==userDetails||!passwordEncoder.matches(password,
                userDetails.getPassword()))
        {
            return RespBean.error("用户名或者密码不正确");
        }
        if(!userDetails.isEnabled())
        {
            return RespBean.error("账号被禁用,请联系管理员");
        }
        System.out.println("success");
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userDetails
                        ,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token=jwtTokenUtil.generateToken(userDetails);
        Map<String,String>map=new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",map);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        QueryWrapper<Admin>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("enabled",true);
        return adminMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq(
                "adminId",adminId));
        Integer integer = adminRoleMapper.addAdminRole(adminId,
                rids);
        if(integer==rids.length)
            return RespBean.success("更新成功!");
        return RespBean.error("更新失败");
    }

    @Override
    public RespBean updateAdminPassword(String oldPass, String pass
            , Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        if(!passwordEncoder.matches(oldPass,admin.getPassword()))
            return RespBean.error("旧密码输入错误!");
        admin.setPassword(passwordEncoder.encode(pass));
        int result = adminMapper.updateById(admin);
        if(1!=result)return RespBean.error("修改密码失败!");
        System.out.println(result);
        return RespBean.success("修改密码成功!");
    }

}
